package com.kucan.recyclecard.core;

import android.content.Context;
import android.os.Handler;

import com.kucan.recyclecard.constants.Constant;
import com.kucan.recyclecard.net.Api;
import com.kucan.recyclecard.net.ApiCallBack;
import com.kucan.recyclecard.net.ApiImpl;
import com.kucan.recyclecard.net.ApiResponse;

public class AppActionImpl implements AppAction{
    private Context mContext;
    private Api api;
    private Handler mHandler = new Handler();

    public AppActionImpl(Context context) {
        this.mContext = context;
        this.api = new ApiImpl(context);
    }

    @Override
    public void getConfig(ActionCallbackListener<String> listener) {
        api.getConfig(new ApiCallBack<ApiResponse<String>>() {
            @Override
            public void onSuccess(ApiResponse<String> data) {
                successHandler(data, listener);
            }

            @Override
            public void onFailure(String errorCode, String message) {
            }
        });
    }

    private void successHandler(final ApiResponse data, final ActionCallbackListener listener) {
        if (data != null && data.data != null) {
            mHandler.post(() -> listener.onSuccess(data.data));
        } else {
            failedHandler(listener, Constant.FAILED, Constant.NULL_DATA_MSG);
        }
    }

    private void failedHandler(final ActionCallbackListener listener, final String errorCode, final String message) {
        mHandler.post(() -> listener.onFailure(errorCode, message));
    }
}
